package com.shenghua.service.impl;

import com.alibaba.fastjson.JSON;
import com.shenghua.dao.mapper.AppFileMapper;
import com.shenghua.dao.mapper.MouldMapper;
import com.shenghua.dao.mapperX.MouldMapperX;
import com.shenghua.dao.model.AppFile;
import com.shenghua.dao.model.AppFileExample;
import com.shenghua.dao.model.Mould;
import com.shenghua.dao.model.MouldExample;
import com.shenghua.dao.page.Page;
import com.shenghua.service.MouldService;
import com.shenghua.utils.ListUtils;
import com.shenghua.utils.PicUtil;
import com.shenghua.utils.StringUtils;
import com.shenghua.utils.beans.Constants;
import com.shenghua.utils.beans.Dto;
import com.shenghua.utils.beans.ErrorCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2018/12/29.
 */
@Service
public class MouldServiceImpl implements MouldService {
    Logger logger = LoggerFactory.getLogger(MouldServiceImpl.class);
    @Autowired
    private MouldMapper mouldMapper;
    @Autowired
    private MouldMapperX mouldMapperX;
    @Autowired
    private AppFileMapper appFileMapper;

    @Override
    public Dto<Mould> addNewMould(Mould mould) {
        Dto<Mould> dto = new Dto<>();
        if(null == mould){
            logger.debug("[MouldServiceImpl] addNewMould 模具信息为空！");
            dto.ReturnFail(new Mould(), ErrorCode.MOULD_IS_NULL);
            return dto;
        }
        MouldExample mouldExample = new MouldExample();
        MouldExample.Criteria criteria = mouldExample.createCriteria();
        if(null != mould.getMouldNo() && !"".equals(mould.getMouldNo())) {
            criteria.andMouldNoEqualTo(mould.getMouldNo());
        } else {
            logger.debug("[MouldServiceImpl] addNewMould 模具编号不能为空！");
            dto.ReturnFail(new Mould(), ErrorCode.MOULDNO_IS_NULL);
            return dto;
        }
        List<Mould> mouldList = mouldMapper.selectByExample(mouldExample);
        if(mouldList.size()>0){
            logger.debug("[MouldServiceImpl] addNewMould 模具编号已经存在！");
            dto.ReturnFail(new Mould(), ErrorCode.MOULDNO_EXISTS);
            return dto;
        }

        mould.setEntryTime(new Date());

        int result = mouldMapperX.insertSelective(mould);
        if(result<=0){
            logger.debug("[MouldServiceImpl] addNewMould 模具信息添加失败！");
            dto.ReturnFail(new Mould(), ErrorCode.MOULD_ADD_FAIL);
            return dto;
        }
        dto.ReturnSuccess(mould,ErrorCode.MOULD_ADD_SUCCESS);
        logger.info("[MouldServiceImpl] addNewMould 模具信息添加成功！");
        logger.info("[MouldServiceImpl] addNewMould 准备添加的模具信息" + JSON.toJSONString(mould));
        return dto;
    }

    @Override
    public Dto<Map<String,Object>> queryMouldByPage(Map<String,Object> params, Page page) {
        Dto<Map<String,Object>> dto = new Dto<>();
        if(null == params || params.size() == 0) {
            logger.debug("[MouldController] selectMouldByPage 参数为空");
            dto.ReturnFail(null, ErrorCode.MOULD_IS_NULL);
            return dto;
        }
        if(null == page){
            logger.debug("[MouldServiceImpl] MouldServiceImpl 分页信息为空");
            dto.ReturnFail(null, ErrorCode.PAGE_IS_NULL);
            return dto;
        }
        SimpleDateFormat sif = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 过滤查询条件
        Map<String,Object> map = new HashMap<>();
        if(null != params.get("mouldNo") && !"".equals(params.get("mouldNo"))){
            map.put("mouldNo",params.get("mouldNo"));
        }
        if(null != params.get("mouldColor") && !"".equals(params.get("mouldColor"))){
            map.put("mouldColor",params.get("mouldColor"));
        }
        if(null != params.get("mouldName") && !"".equals(params.get("mouldName"))){
            map.put("mouldName",params.get("mouldName"));
        }
        if(null != params.get("spec") && !"".equals(params.get("spec"))){
            map.put("spec",params.get("spec"));
        }
        if(null != params.get("startTime") && !params.get("startTime").equals("") && null != params.get("endTime") && !params.get("endTime").equals("")){
            Date start = null;
            Date end = null;
            try {
                start = sif.parse(params.get("startTime").toString());
                end = sif.parse(params.get("endTime").toString());
            } catch (ParseException e) {
                logger.info("[MouldController] selectMouldByPage 时间解析异常！");
                e.printStackTrace();
            }
            map.put("startTime", start);
            map.put("endTime", end);
        }
        map.put("begin", page.getBegin());
        map.put("end", page.getLength());
        int total = 0;
        List<Mould> list = new ArrayList<>();
        List<Mould> list1 = null;
        list1 = mouldMapperX.selectMouldListByMap(map);
        if(ListUtils.isNotEmpty(list1)) {
            for (Mould mould : list1) {
                if (!StringUtils.isBlank(mould.getPicAddr())) {
                    mould.setPicAddr(Constants.staticPrefix + mould.getPicAddr());
                }
                list.add(mould);
            }
        }
        total = mouldMapperX.countMouldByMap(map);
        logger.info("***********************");
        logger.info("查询到的记录总数："+String.valueOf(total));
        logger.info("查询到的记录信息："+JSON.toJSONString(list));
        logger.info("***********************");
        // 返回数据
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("total",total);
        paramMap.put("rows", list);
        dto.ReturnSuccess(paramMap,ErrorCode.MOULD_Query_SUCCESS);
        return dto;
    }

    @Override
    public Dto<Mould> deleteMould(Mould mould) {
        Dto<Mould> dto = new Dto<>();
        int id = mould.getId();

        AppFileExample appFileExample = new AppFileExample();
        AppFileExample.Criteria criteria = appFileExample.createCriteria();
        criteria.andFileBelongtoEqualTo(String.valueOf(id));
        appFileMapper.deleteByExample(appFileExample);

        int count =mouldMapper.deleteByPrimaryKey(id);
        if(count <= 0){
            logger.debug("[MouldServiceImpl] deleteMould 模具删除失败！");
            dto.ReturnFail(mould,ErrorCode.MOULD_DELETE_FAIL);
            return dto;
        }
        /*String picAddr = mould.getPicAddr();
        if(null != picAddr && !"".equals(picAddr)) {// 删除图片
            if(!new File(picAddr).exists()) {
                logger.debug("[MouldServiceImpl] deleteMould 模具图片不存在！");
                dto.ReturnSuccess(mould,ErrorCode.MOULD_PIC_NOT_EXISTS);
                return dto;
            } else {
                boolean ret = PicUtil.DeleteImage(picAddr);
                if(!ret){
                    logger.debug("[MouldServiceImpl] deleteMould 模具图片删除失败！");
                    dto.ReturnSuccess(mould,ErrorCode.MOULD_DELETE_PIC_FAIL);
                    return dto;
                }
            }
        }*/
        logger.info("[MouldServiceImpl] deleteMould 模具删除成功！");
        dto.ReturnSuccess(mould,ErrorCode.MOULD_DELETE_SUCCESS);
        return dto;
    }

    @Override
    public Mould selectMouldById(int id) {
        Mould mould = mouldMapper.selectByPrimaryKey(id);
        return mould;
    }

    @Override
    public Dto<Mould> editMould(Mould mould) {
        Dto<Mould> dto = new Dto<>();
        Mould mould1 = mouldMapper.selectByPrimaryKey(mould.getId());
        if(null == mould1) {
            logger.debug("[MouldServiceImpl] editMould 模具不存在！");
            dto.ReturnFail(new Mould(),ErrorCode.MOULD_NOT_EXISTS);
            return dto;
        }
        mould1.setMouldColor(mould.getMouldColor());
        mould1.setMouldName(mould.getMouldName());
        mould1.setSpec(mould.getSpec());
        mould1.setModelNo(mould.getModelNo());
        mould1.setMaterial(mould.getMaterial());
        mould1.setMouldClz(mould.getMouldClz());
        mould1.setScope(mould.getScope());
        mould1.setRemark(mould.getRemark());
        mould1.setUpdateUserid(mould.getUpdateUserid());
        mould1.setUpdateNickname(mould.getUpdateNickname());
        mould1.setPicAddr(mould.getPicAddr());
        mould1.setUpdateTime(new Date());

        int count = mouldMapper.updateByPrimaryKeySelective(mould1);
        if(count <= 0){
            logger.debug("[MouldServiceImpl] editMould 模具编辑失败！");
            mould.setPicAddr(Constants.staticPrefix + mould.getPicAddr());
            dto.ReturnFail(mould, ErrorCode.MOULD_EDIT_FAIL);
            return dto;
        }
        logger.info("[MouldServiceImpl] editMould 模具编辑成功！");
        mould.setPicAddr(Constants.staticPrefix + mould.getPicAddr());
        dto.ReturnSuccess(mould,ErrorCode.MOULD_EDIT_SUCCESS);
        return dto;
    }

    @Override
    public Dto<Map<String, Object>> countMould(Map<String, Object> params) {
        Dto<Map<String,Object>> dto = new Dto<>();
        if(null == params || params.size() == 0) {
            logger.debug("[MouldController] countMould 参数为空");
            dto.ReturnFail(null, ErrorCode.MOULD_IS_NULL);
            return dto;
        }
        SimpleDateFormat sif = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 过滤查询条件
        Map<String,Object> map = new HashMap<>();
        if(null != params.get("mouldNo") && !"".equals(params.get("mouldNo"))){
            map.put("mouldNo",params.get("mouldNo"));
        }
        if(null != params.get("mouldColor") && !"".equals(params.get("mouldColor"))){
            map.put("mouldColor",params.get("mouldColor"));
        }
        if(null != params.get("mouldName") && !"".equals(params.get("mouldName"))){
            map.put("mouldName",params.get("mouldName"));
        }
        if(null != params.get("spec") && !"".equals(params.get("spec"))){
            map.put("spec",params.get("spec"));
        }
        if(null != params.get("startTime") && !params.get("startTime").equals("") && null != params.get("endTime") && !params.get("endTime").equals("")){
            Date start = null;
            Date end = null;
            try {
                start = sif.parse(params.get("startTime").toString());
                end = sif.parse(params.get("endTime").toString());
            } catch (ParseException e) {
                logger.info("[MouldController] countMould 时间解析异常！");
                e.printStackTrace();
            }
            map.put("startTime", start);
            map.put("endTime", end);
        }
        int total = 0;
        total = mouldMapperX.countMouldByMap(map);
        logger.info("***********************");
        logger.info("查询到的记录总数："+String.valueOf(total));
        logger.info("***********************");
        // 返回数据
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("total",total);
        dto.ReturnSuccess(paramMap,ErrorCode.MOULD_Query_SUCCESS);
        return dto;
    }

    @Override
    public Dto<Map<String, Object>> queryMouldSwiper() {
        Dto<Map<String,Object>> dto = new Dto<>();
        SimpleDateFormat sif = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        /*if(null != params.get("startTime") && !params.get("startTime").equals("") && null != params.get("endTime") && !params.get("endTime").equals("")){
            Date start = null;
            Date end = null;
            try {
                start = sif.parse(params.get("startTime").toString());
                end = sif.parse(params.get("endTime").toString());
            } catch (ParseException e) {
                logger.info("[MouldController] selectMouldByPage 时间解析异常！");
                e.printStackTrace();
            }
            map.put("startTime", start);
            map.put("endTime", end);
        }
        map.put("begin", page.getBegin());
        map.put("end", page.getLength());*/
        int total = 0;
        List<Mould> list = new ArrayList<>();
        List<Mould> list1 = null;
        list1 = mouldMapperX.selectMouldListByMap(new TreeMap<String, Object>());
        if(ListUtils.isNotEmpty(list1)) {
            for (Mould mould : list1) {
                if (!com.shenghua.utils.StringUtils.isBlank(mould.getPicAddr())) {
                    mould.setPicAddr(Constants.staticPrefix + mould.getPicAddr());
                }
                list.add(mould);
            }
        }

        logger.info("***********************");
        logger.info("查询到的记录信息："+JSON.toJSONString(list));
        logger.info("***********************");
        // 返回数据
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("rows", list);
        dto.ReturnSuccess(paramMap,ErrorCode.MOULD_Query_SUCCESS);
        return dto;
    }
}
